package cc.customer.center.Impl;

import cc.customer.center.SaleCusManagerServices;
import cc.customer.common.domain.QueryRequest;
import cc.customer.common.domain.ResponseBo;
import cc.customer.common.service.impl.BaseService;
import cc.customer.common.utils.DateUtil;
import cc.customer.cusDynamic.dao.CusDynamicMapper;
import cc.customer.myCustomer.damain.CusResource;
import cc.customer.myCustomer.dao.CusResourceMapper;
import cc.customer.system.dao.SaleTagMapper;
import cc.customer.system.domain.MyUser;
import cc.customer.system.domain.SaleTag;
import cc.customer.system.service.UserService;
import cc.customer.utils.AutonCusInfo;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class SaleCusManagerServicesImp extends BaseService<CusResource> implements SaleCusManagerServices {

    private static final Logger logger = LoggerFactory.getLogger(SaleCusManagerServicesImp.class);

    @Autowired
    private CusResourceMapper cusResourceMapper;
    @Autowired
    private UserService userMapper;
    @Autowired
    private SaleTagMapper saleTagMapper;
    @Autowired
    private CusDynamicMapper dynamicMapper;

    @Override
    public List<CusResource> selectCusReManageList(CusResource cusResource,MyUser users) {
        try {
            /**查询包含标签**/
            String label = cusResource.getLabel();//包含标签
            if (!StringUtils.isEmpty(label)){
                List<String> list = Arrays.asList(label.split(","));
                cusResource.setContainLabel(list);
            }
            /**查询不包含标签**/
            String notLabel = cusResource.getNotLabel();
            if (!StringUtils.isEmpty(notLabel)){
                List<String> list = Arrays.asList(notLabel.split(","));
                cusResource.setNotcontainLabel(list);
            }
            /**时间格式化**/
            String starttime = cusResource.getBeforeTime();
            String endtime = cusResource.getAfterTime();
            if (!StringUtils.isEmpty(starttime) && !StringUtils.isEmpty(endtime)){
                String timestart = starttime+" 00:00:00";
                String timeend = endtime+" 23:59:59";
                cusResource.setBeforeTime(timestart); cusResource.setAfterTime(timeend);
            }
            List<CusResource> list  = cusResourceMapper.selectCusReManageList(cusResource);
            for (CusResource cusResourcelist:list){
                String labelselect = cusResourcelist.getLabel();
                if (!StringUtils.isEmpty(labelselect)){
                    Example example = new Example(SaleTag.class);
                    example.createCriteria().andIn("tagUuids",Arrays.asList(labelselect.split(",")));
                    List<SaleTag> saleTags = saleTagMapper.selectByExample(example);
                    StringBuilder sb = new StringBuilder();
                    for (SaleTag saleTag :saleTags){
                        sb.append(saleTag.getTagName()+",");
                    }
                    int lastIndes = sb.lastIndexOf(",");
                    if (lastIndes >0){
                        cusResourcelist.setLabel(sb.substring(0,lastIndes));
                    }
                }
                String userid = cusResourcelist.getReceiver();
                if (!StringUtils.isEmpty(userid)){
                    Example example = new Example(MyUser.class);
                    example.createCriteria().andIn("userUuid",Arrays.asList(userid.split(",")));
                    List<MyUser> myUsers = userMapper.selectByExample(example);
                    StringBuilder sb = new StringBuilder();
                    for (MyUser user :myUsers){
                        sb.append(user.getNickname()+",");
                    }
                    int lastIndes = sb.lastIndexOf(",");
                    if (lastIndes >0){
                        cusResourcelist.setReceiver(sb.substring(0,lastIndes));
                    }
                }

                AutonCusInfo.parseResource(cusResourcelist,users);
            }
            return list;
        }catch (Exception e){
            e.printStackTrace();
            return new ArrayList<>();
        }
    }
    @Override
    public ResponseBo  selectCusCustomerList(CusResource cusResource) {
        try {
            /**查询包含标签**/
            String label = cusResource.getLabel();//包含标签
            if (!StringUtils.isEmpty(label)){
                List<String> list = Arrays.asList(label.split(","));
                cusResource.setContainLabel(list);
            }
            /**查询不包含标签**/
            String notLabel = cusResource.getNotLabel();
            if (!StringUtils.isEmpty(notLabel)){
                List<String> list = Arrays.asList(notLabel.split(","));
                cusResource.setNotcontainLabel(list);
            }
            //获取名字信息
            List<String> legend = new ArrayList<>();
            //读取人员id 方便查找
            List<String> legendUid = new ArrayList<>();
            String ninckname = cusResource.getNickname();
            if (StringUtils.isEmpty(ninckname)){
                legend.add("客户总数");
            }else{
                /**人员名称分批处理**/
                List<String>lust = Arrays.asList(ninckname.split(","));
                legend.addAll(lust);
                /**人员Uid分批处理**/
                String userid = cusResource.getUserid();
                List<String> listUid = Arrays.asList(userid.split(","));
                legendUid.addAll(listUid);
            }
            List<String> xAxis = new ArrayList<>();
            /**时间格式化查询 如果开始时间是7 则表示 查询7天之内,如果是30 则表示查询30天得**/
            String starttime = cusResource.getBeforeTime();
            if("7".equals(starttime)){
                Date week = DateUtil.addDays(new Date(),-7);
                for (int i=0; i<7; i++){
                    Date thisdate = DateUtil.addDays(week,i);
                    String datestr = DateUtil.convert2String(thisdate,"yyyy-MM-dd");
                    xAxis.add(datestr);
                }
            }else if ("30".equals(starttime)){
                Date month = DateUtil.addDays(new Date(),-30);
                for (int j=0; j<30; j++){
                    Date thisdate = DateUtil.addDays(month,j);
                    String datestr = DateUtil.convert2String(thisdate,"yyyy-MM-dd");
                    xAxis.add(datestr);
                }
            }else{
                String endtime = cusResource.getAfterTime();
                if (!StringUtils.isEmpty(starttime) && !StringUtils.isEmpty(endtime)){
                    Date st = DateUtil.convert2Date(starttime,"yyyy-MM-dd");
                    Date et = DateUtil.convert2Date(endtime,"yyyy-MM-dd");
                    int diff =  DateUtil.diffDay(st,et);
                    xAxis.add(DateUtil.convert2String(st,"yyyy-MM-dd"));
                   if (diff > 30){//如果大于 30天 则相差一个星期展示 比较是否差别一年 54*7
                       for (int k=0; k<54;k++){
                           Date tihdate = DateUtil.addDays(st,7);
                           int diffdate = DateUtil.diffDay(tihdate,et);
                           //比较差 如果 相差少于10天 默认是最后一个日期
                           if (diffdate <= 10 ){
                               xAxis.add(DateUtil.convert2String(et,"yyyy-MM-dd"));
                               break;
                           }else{
                               xAxis.add(DateUtil.convert2String(tihdate,"yyyy-MM-dd"));
                           }
                           st = tihdate;
                       }
                   }else{//如果小于 30天
                       for (int f=1; f<diff; f++){
                           Date thisdate = DateUtil.addDays(st,f);
                           String datestr = DateUtil.convert2String(thisdate,"yyyy-MM-dd");
                           xAxis.add(datestr);
                       }
                   }
                }
            }
            /**循环人查询每个人得,每个时间段得信息**/
            JSONArray jsonService = new JSONArray();
            /**table 数据**/
            JSONArray jsonArrTable = new JSONArray();
            if (legendUid.isEmpty()){
                JSONObject json = new JSONObject();
                json.put("name","客户总数");
                json.put("type","line");
                json.put("stack","总量");
                JSONArray jsonArray = new JSONArray();
                for (String date:xAxis){
                    String start  = "2017-04-28 00:00:00"; //默认从2000年计时
                    String end = date+" 23:59:59";
                    cusResource.setBeforeTime(start);
                    cusResource.setAfterTime(end);
                    cusResource.setDelstatus("0");
                    int num = cusResourceMapper.selectCusIndexList(cusResource);

                    JSONObject jsonTable = new JSONObject();
                    jsonTable.put("time",date);
                    /**查询当天删除**/
                    String custart = date+" 00:00:00";
                    cusResource.setDelstatus("1");
                    cusResource.setBeforeTime(custart);
                    int numdelete  = dynamicMapper.selectGiveUpCount(custart,end);//cusResourceMapper.selectCusIndexList(cusResource);
                    jsonTable.put("delete",numdelete);
                    /**查询新建**/
                    cusResource.setDelstatus("0");
                    int numadd = cusResourceMapper.selectCusIndexList(cusResource);
                    jsonTable.put("add",numadd);
                    jsonTable.put("all",num);
                    jsonArrTable.add(jsonTable);
                    jsonArray.add(num);
                }
                json.put("data",jsonArray);
                jsonService.add(json);
            }else{
                for (int i=0;i<legend.size();i++) {
                    JSONObject json = new JSONObject();
                    json.put("name",legend.get(i));
                    json.put("type","line");
                    json.put("stack","总量");
                    JSONArray jsonArray = new JSONArray();
                    List<String> listUid = new ArrayList<>();
                    String uuids = legendUid.get(i);
                    if (uuids.contains("jpet")){
                        String deptid = uuids.replace("jpet","");
                        Example example = new Example(MyUser.class);
                        example.createCriteria().andEqualTo("deptId",deptid).andEqualTo("status","1");
                        List<MyUser> listall =  userMapper.selectByExample(example);
                        for (MyUser user:listall){
                            listUid.add(user.getUserUuid());
                        }
                    }else{
                        listUid.add(uuids);
                    }
                    for (String date:xAxis){
                        String start  = "2017-04-28 00:00:00"; //默认从2000年计时
                        String end = date+" 23:59:59";
                        cusResource.setBeforeTime(start);
                        cusResource.setAfterTime(end);
                        cusResource.setListUsers(listUid);
                        cusResource.setDelstatus("0");
                        int num  = cusResourceMapper.selectCusIndexList(cusResource);

                        JSONObject jsonTable = new JSONObject();
                        jsonTable.put("time",date);
                        /**查询当天删除**/
                        String custart = date+" 00:00:00";
                        cusResource.setDelstatus("1");
                        cusResource.setBeforeTime(custart);
                        int numdelete  = dynamicMapper.selectGiveUpCount(custart,end);
                        jsonTable.put("delete",numdelete);
                        /**查询新建**/
                        cusResource.setDelstatus("0");
                        int numadd = cusResourceMapper.selectCusIndexList(cusResource);
                        jsonTable.put("add",numadd);
                        jsonTable.put("all",num);
                        jsonArrTable.add(jsonTable);

                        jsonArray.add(num);
                    }
                    json.put("data",jsonArray);
                    jsonService.add(json);
                }
            }

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("legend",legend);
            //重置日期 改变日期得年份
            JSONArray json = new JSONArray();
            for (String axis :xAxis){
                String min = axis.substring(5);
                json.add(min);
            }
            jsonObject.put("xAxis",json);
            jsonObject.put("series",jsonService);

            /**查询每个日期 流失得 新增得 总数**/
            jsonObject.put("table",jsonArrTable);
            return ResponseBo.ok(jsonObject);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("获取销售管理-客户数据统计失败:"+e.getMessage());
        }
        return ResponseBo.error("获取销售管理-客户数据统计失败");
    }





}
